

<template>
  <zc-card>
    <div class="calendar-list-container">
      <!-- <basic-container> -->
      <div class="filter-container" v-if="development">
        <el-button-group>
          <el-button type="primary" icon="plus" v-if="this.treeData[0].children.length>0" @click="delallsynmenu"
            >清空菜单</el-button
          >
          <el-button type="primary" v-if="this.treeData[0].children.length==0" icon="plus" @click="synchronization"
            >同步本地菜单</el-button
          >
          <el-button
            type="primary"
            icon="plus"
            v-if="menuManager_btn_add"
            @click="handlerAdd"
            >添加</el-button
          >
          <el-button
            type="primary"
            icon="edit"
            v-if="menuManager_btn_edit"
            @click="handlerEdit"
            >编辑</el-button
          >
          <el-button
            type="primary"
            icon="delete"
            v-if="menuManager_btn_del"
            @click="handleDelete"
            >删除</el-button
          >
        </el-button-group>
      </div>
      <el-row>
        <el-col :span="4" style="margin-top: 15px">
          <el-tree
            class="filter-tree"
            node-key="id"
            highlight-current
            :data="treeData"
            :default-expanded-keys="aExpandedKeys"
            :filter-node-method="filterNode"
            :props="defaultProps"
            @node-click="getNodeData"
            @node-expand="nodeExpand"
            @node-collapse="nodeCollapse"
          ></el-tree>
        </el-col>
        <el-col :span="10" :offset="1" style="margin-top: 15px">
          <!-- <el-card class="box-card"> -->
          <el-form
            :label-position="labelPosition"
            label-width="80px"
            :model="form"
            ref="form"
          >
            <el-form-item label="父级节点" prop="p_id">
              <el-input v-model="form.p_id" ></el-input>
            </el-form-item>
            <el-form-item
              v-if="formStatus !== 'create'"
              label="节点ID"
              prop="menuId"
            >
              <el-input v-model="form.menuId" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="主标题" prop="name">
              <el-input
                v-model="form.name"
                :disabled="formEdit"
                placeholder="请输入标题"
              ></el-input>
            </el-form-item>
            <el-form-item label="标题" prop="title">
              <el-input
                v-model="form.title"
                :disabled="formEdit"
                placeholder="请输入标题"
              ></el-input>
            </el-form-item>
            <el-form-item label="权限标识" prop="permission">
              <el-input
                v-model="form.permission"
                :disabled="formEdit"
                placeholder="请输入权限标识"
              ></el-input>
            </el-form-item>
            <el-form-item label="图标">
              <avue-input-icon
                v-model="form.icon"
                placeholder="请选择图标"
                :disabled="formEdit"
                :icon-list="iconList"
              ></avue-input-icon>
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-select
                class="filter-item"
                v-model="form.type"
                :disabled="formEdit"
                placeholder="请输入权限类型"
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item"
                  :label="item | typeFilter"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input
                type="number"
                v-model="form.sort"
                :disabled="formEdit"
                placeholder="请输入排序"
              ></el-input>
            </el-form-item>
            <el-form-item label="重定向" prop="redirect">
              <el-input
                v-model="form.redirect"
                :disabled="formEdit"
                placeholder="请输入前端重定向"
              ></el-input>
            </el-form-item>
            <el-form-item label="前端path" prop="path">
              <el-input
                v-model="form.path"
                :disabled="formEdit"
                placeholder="请输入描述"
              ></el-input>
            </el-form-item>
            <!-- <el-form-item label="前端name" prop="component">
              <el-input v-model="form.path" :disabled="formEdit" placeholder="iframe嵌套地址"></el-input>
              </el-form-item>-->
            <el-form-item label="生成权限" prop="is_cache">
              <el-switch
                v-model="form.is_cache"
                :disabled="formEdit"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="2"
              ></el-switch>
            </el-form-item>
            <el-form-item v-if="formStatus == 'update'">
              <el-button type="primary" @click="update">更新</el-button>
              <el-button @click="onCancel">取消</el-button>
            </el-form-item>
            <el-form-item v-if="formStatus == 'create'">
              <el-button type="primary" @click="create">添加</el-button>
              <el-button @click="onCancel">取消</el-button>
            </el-form-item>
          </el-form>
          <!-- </el-card> -->
        </el-col>
      </el-row>
      <!-- </basic-container> -->
    </div>
  </zc-card>
</template>

<script>
import {
  fetchList,
  findOne,
  update,
  create,
  del,
  all_add,
} from "@/api/admin/menu";
import baseIconList from "./baseIconList";
import { asyncRoutes } from "@/router/index";
import { mapGetters } from "vuex";
import { remove } from "js-cookie";

export default {
  name: "menu",
  data() {
    return {
      iconList: [
        {
          label: "基本图标",
          list: baseIconList,
        },
        {
          label: "方向图标",
          list: [
            "el-icon-caret-left",
            "el-icon-caret-right",
            "el-icon-caret-bottom",
            "el-icon-caret-top",
            "el-icon-bottom-left",
            "el-icon-bottom-right",
            "el-icon-back",
            "el-icon-right",
            "el-icon-bottom",
            "el-icon-top",
            "el-icon-top-left",
            "el-icon-top-right",
            "el-icon-arrow-left",
            "el-icon-arrow-right",
            "el-icon-arrow-down",
            "el-icon-arrow-up",
            "el-icon-d-arrow-left",
            "el-icon-d-arrow-right",
          ],
        },
        {
          label: "符号图标",
          list: [
            "el-icon-plus",
            "el-icon-minus",
            "el-icon-close",
            "el-icon-check",
          ],
        },
        {
          label: "其他图标",

          list: [
            "iconfont icon-zhengfujiguan",
            "iconfont icon-caigoudingdan",
            "iconfont icon-zhengfugongbao",
            "iconfont icon-zhengfugongzuobaogao",
            "iconfont icon-jihuashu",
            "iconfont icon-wj-jh",
            "iconfont icon-zhengfujigou",
            "iconfont icon-shengzhengfugongbao",
            "iconfont icon-shengzhengfuchangwuhuiyi",
            "iconfont icon-huanyingye",
            "iconfont icon-shujuzhanshi2",
            "iconfont icon-weixin1",
            "iconfont icon-cuowutishitubiao",
            "iconfont icon-iconset0216",
            "iconfont icon-iconset0265",
            "iconfont icon-quanping",
            "iconfont icon-iframe",
            "iconfont icon-wxbgongju",
            "iconfont icon-biaodan",
            "iconfont icon-qq",
            "iconfont icon-msnui-360",
            "iconfont icon-tuichu",
            "iconfont icon-souhu",
            "iconfont icon-weixin",
            "iconfont icon-changyonglogo27",
            "iconfont icon-tuichuquanping",
            "iconfont icon-qq1",
            "iconfont icon-yanzhengma",
            "iconfont icon-tubiao",
            "iconfont icon-huanyingye",
            "iconfont icon-bug",
            "iconfont icon-qq1",
            "iconfont icon-weixin1",
          ],
        },
      ],

      list: null,
      total: null,
      formEdit: true,
      formAdd: true,
      development: process.env.NODE_ENV == "development",
      formStatus: "",
      showElement: false,
      typeOptions: ["1", "2", "3"],
      methodOptions: ["GET", "POST", "PUT", "DELETE"],
      listQuery: {
        name: undefined,
      },
      treeData: [],
      oExpandedKey: {
        // key (from tree id) : expandedOrNot boolean
      },
      oTreeNodeChildren: {
        // id1 : [children] (from tree node id1)
        // id2 : [children] (from tree node id2)
      },
      aExpandedKeys: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      labelPosition: "right",
      form: {
        redirect: "",
        permission: "",
        name: "",
        menuId: "",
        p_id: "",
        icon: "",
        sort: "",
        component: "",
        type: "",
        path: "",
      },
      currentId: -1,
      menuManager_btn_add: false,
      menuManager_btn_edit: false,
      menuManager_btn_del: false,
    };
  },
  filters: {
    typeFilter(type) {
      const typeMap = {
        1: "目录",
        2: "菜单",
        3: "按钮",
      };
      return typeMap[type];
    },
  },
  created() {
    this.getList();
    // v-if="process.env.NODE_ENV == 'development'"
    console.log();
    console.log(asyncRoutes, "本地菜单");
    const role = this.$defaultRoleStatus;

    this.menuManager_btn_add = this.zcbtn[this.$options.name + "_add"] || role;
    this.menuManager_btn_edit =
      this.zcbtn[this.$options.name + "_edit"] || role;
    this.menuManager_btn_del = this.zcbtn[this.$options.name + "_del"] || role;
  },
  computed: {
    ...mapGetters(["zcrouter", "zcbtn"]),
  },
  methods: {
    delallsynmenu(){//清空服务器的菜单
 //删除线上菜单
 var delmenuids=[];
      if (this.treeData[0].children.length > 0) {
        //如果有线上菜单，先清空线上菜单
        this.treeData[0].children.forEach((item) => {
          item.children.forEach((mpage) => {
            // console.log(menu.name)
            mpage.children.forEach((btn) => {
              delmenuids.push(btn.id)
              // del({ id: btn.id }).then(() => {
              //   console.log("按钮-->" + btn.name + "==>删除");
              // }); //删除按钮
            });
            delmenuids.push(mpage.id)
            // del({ id: mpage.id }).then(() => {
            //   console.log("页面-->" + mpage.name + "==>删除");
            // }); //删除页面
          });
          delmenuids.push(item.id)
          // del({ id: item.id }).then(() => {
          //   console.log("目录-->" + item.name + "==>删除");
          // }); //删除目录
        });
        let dmid=0;
        delmenu(dmid)
        var that=this
        function delmenu(){
        
          del({ id:delmenuids[dmid], }).then(() => {
               if(dmid<delmenuids.length-1){
                dmid++
                delmenu(dmid)
               }else{
                that.getList();
               }
              }); //删除按钮
        }
      }
    },
    //同步本地菜单
    synchronization() {
     
      //新增本地菜单
      //菜单整理
      var newmenu = []; //建立本地菜单数组
      // this.permission.addBtn = this.zcbtn[this.$options.name + '_add'] || role
      //     this.permission.editBtn = this.zcbtn[this.$options.name + '_edit'] || role
      //     this.permission.delBtn = this.zcbtn[this.$options.name + '_del'] || role
      asyncRoutes.forEach((item, mdx) => {
        //循环本地一级目录
        let menuarr = [];
        // console.log(item.meta.title)

        item.children?.forEach((mpage, pdx) => {
          // console.log(mpage.meta.title)
          //循环本地菜单
          let btnarr = [
            //建立按钮权限
            {
              name: mpage.meta.title + "添加",
              meta:{
                title:mpage.meta.title + "添加",
                icon:'',
                i18n:'i18n',
                keepAlive:'keepAlive',
              },
              redirect: "",
              path: "",
              icon: "",
              iconBgColor: "",
              is_cache: 2,
              is_show: 0,
              sign: mpage.path + "_add",
              sort: 1,
              type: 3,
            },
            {
              meta:{
                title:mpage.meta.title + "编辑",
                icon:'',
                i18n:'i18n',
                keepAlive:'keepAlive',
              },
              name: mpage.meta.title + "编辑",
              redirect: "",
              path: "",
              icon: "",
              iconBgColor: "",
              is_cache: 2,
              is_show: 0,
              sign: mpage.path + "_edit",
              sort: 2,
              type: 3,
            },
            {
              meta:{
                title:mpage.meta.title + "删除",
                icon:'',
                i18n:'i18n',
                keepAlive:'keepAlive',
              },
              name: mpage.meta.title + "删除",
              redirect: "",
              path: "",
              icon: "",
              iconBgColor: "",
              is_cache: 2,
              is_show: 0,
              sign: mpage.path + "_del",
              sort: 3,
              type: 3,
            },
            {
              meta:{
                title:mpage.meta.title + "导出表格",
                icon:'',
                i18n:'i18n',
                keepAlive:'keepAlive',
              },
              name: mpage.meta.title + "导出表格",
              redirect: "",
              path: "",
              icon: "",
              iconBgColor: "",
              is_cache: 2,
              is_show: 0,
              sign: mpage.path + "_excel",
              sort: 4,
              type: 3,
            },
          ];
          if(mpage.path=='role'){
            btnarr.push({
              meta:{
                title:'权限分配',
                icon:'',
                i18n:'i18n',
                keepAlive:'keepAlive',
              },
              name: '权限分配',
              redirect: "",
              path: "",
              icon: "",
              iconBgColor: "",
              is_cache: 2,
              is_show: 0,
              sign: "role_distribution",
              sort: 5,
              type: 3,
            },)
          }
          // console.log('按钮权限',btnarr)
          let menuobj = {
            meta:mpage.meta,
            name: mpage.meta.title,
            redirect: mpage.redirect,
            path: mpage.path,
            icon: mpage.icon,
            iconBgColor: mpage.iconBgColor,
            is_cache: 2,
            is_show: mpage.hidden ? 1 : 0,
            sign: mpage.path,
            sort: pdx + 1,
            type: 2,
            children: btnarr,
          };
          menuarr.push(menuobj);
        });
        console.log(item);
        newmenu.push({
          meta:item.meta,
          name: item.meta.title,
          redirect: item.redirect,
          path: item.path,
          icon: item.icon,
          iconBgColor: item.iconBgColor,
          is_cache: 2,
          is_show: item.hidden ? 1 : 0,
          sign: item.name,
          sort: mdx + 1,
          type: 1,
          children: menuarr,
        });
      });
      console.log(newmenu);
      all_add({ json_all: JSON.stringify(newmenu) }).then((res) => {
        this.getList();
      });
    },
    // 获取菜单
    getList() {
      fetchList(this.listQuery).then((res) => {
        let arr = [{ id: 0, p_id: 0, name: "菜单", children: res }];
        // console.log(arr);
        this.treeData = arr;
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    nodeExpand(data) {
      let aChildren = data.children;
      if (aChildren.length > 0) {
        this.oExpandedKey[data.id] = true;
        this.oTreeNodeChildren[data.id] = aChildren;
      }
      this.setExpandedKeys();
    },
    nodeCollapse(data) {
      this.oExpandedKey[data.id] = false;
      // 如果有子节点
      this.treeRecursion(this.oTreeNodeChildren[data.id], (oNode) => {
        this.oExpandedKey[oNode.id] = false;
      });
      this.setExpandedKeys();
    },
    setExpandedKeys() {
      let oTemp = this.oExpandedKey;
      this.aExpandedKeys = [];
      for (let sKey in oTemp) {
        if (oTemp[sKey]) {
          this.aExpandedKeys.push(parseInt(sKey));
        }
      }
    },
    treeRecursion(aChildren, fnCallback) {
      if (aChildren) {
        for (let i = 0; i < aChildren.length; ++i) {
          let oNode = aChildren[i];
          fnCallback && fnCallback(oNode);
          this.treeRecursion(oNode.children, fnCallback);
        }
      }
    },
    // 获取节点数据
    getNodeData(data) {
      // console.log(data);
      if (!this.formEdit) {
        this.formStatus = "update";
      }
      // console.log(this.form);
      if (data.id == 0) {
        this.resetForm();
        (this.form.menuId = 0), (this.form.p_id = 0);
        return;
      }
      findOne({ id: data.id }).then((res) => {
        // console.log(res, "请求后");
        let obj = {
          menuId: res.id,
          name: res.name,
          title: res.meta.title,
          permission: res.sign,
          icon: res.meta.icon,
          type: res.type + "",
          sort: res.sort,
          redirect: res.redirect,
          path: res.path,
          p_id: res.p_id,
          is_cache: res.is_cache,
        };
        this.form = obj;
      });
      // this.currentId = data.p_id;
      this.showElement = true;
    },
    handlerEdit() {
      if (this.form.menuId) {
        this.formEdit = false;
        this.formStatus = "update";
      }
    },
    handlerAdd() {
      let id = this.form.menuId;
      this.resetForm();
      this.form.p_id = id;
      this.formEdit = false;
      this.formStatus = "create";
    },
    handleDelete() {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        del({ id: this.form.menuId }).then(() => {
          this.getList();
          this.resetForm();
          this.onCancel();
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
            duration: 2000,
          });
        });
      });
    },
    update() {
      // console.log(this.form);
      let item = this.form;

      let params = {
        id: item.menuId,
        name: item.name,

        meta_title: item.title,
        sign: item.permission,
        meta_icon: item.icon,
        type: item.type,
        sort: item.sort,
        redirect: item.redirect,
        path: item.path,
        p_id: item.p_id,
        is_cache: item.is_cache,
      };
      // console.log(params);

      update(params).then(() => {
        this.getList();
        this.$notify({
          title: "成功",
          message: "更新成功",
          type: "success",
          duration: 2000,
        });
      });
    },
    create() {
      let item = this.form;
      let params = {
        name: item.name,
        meta_title: item.title,
        sign: item.permission,
        meta_icon: item.icon,
        type: item.type,
        sort: item.sort,
        redirect: item.redirect,
        path: item.path,
        p_id: item.p_id,
        is_cache: item.is_cache,
      };
      create(params).then(() => {
        this.getList();
        this.$notify({
          title: "成功",
          message: "创建成功",
          type: "success",
          duration: 2000,
        });
      });
    },
    onCancel() {
      this.formEdit = true;
      this.formStatus = "";
    },
    resetForm() {
      this.form = {
        p_id: this.currentId, // 父id
        menuId: undefined, // 自己id
        name: "", // 标题
        title: "", // mate 中的title
        permission: "", // 权限标识
        is_cache: 2, // 是否缓存  1 是 2否
        icon: undefined, // 图标
        sort: undefined, // 排序
        type: undefined, // 类型
        redirect: "", // 重定向地址
        path: "", // 前端路由
        component: undefined,
      };
    },
  },
  watch: {},
  mounted() {
    // let gouride = document.getElementsByClassName("el-dialog__header")[3];
    // gouride.style = "display:none";
    // console.log();
  },
};
</script>

<style scoped>
.avue-form /deep/ .el-form-item__content {
  margin-left: 0 !important;
}
.avue-form /deep/ .avue-form__row {
  padding: 0 !important;
}
</style>
